<?php
/**
 * @package YARBB
 * @copyright Авторские права (C) 2009 www.yar-it.com. Все права защищены.
 * @license Лицензия http://www.gnu.org/licenses/gpl-2.0.htm GNU/GPL, или help/license.php
 * YARBB! - свободное программное обеспечение распространяемое по условиям лицензии GNU/GPL
 * Для получения информации о используемых расширениях и замечаний об авторском праве, смотрите файл copyright.php.
 */

// no direct access
defined( '_VALID_MOS' ) or die();

//запрет чтения форума группе
if ($yarbb_user['g_read_board'] == '0') {
    mosRedirect(sefRelToAbs(YARBB_URL.'&amp;task=access&amp;action=noperm'));
}
mosCommonHTML::loadJquery();
//редактор бб кода
$mainframe->addJS($yarbb_live.'/theme/'.$yarbb_config['o_default_style'].'/plugins/markitup/jquery.markitup.js'); 
$mainframe->addCSS($yarbb_live.'/theme/'.$yarbb_config['o_default_style'].'/plugins/markitup/skins/markitup/style.css');
$mainframe->addCSS($yarbb_live.'/theme/'.$yarbb_config['o_default_style'].'/plugins/markitup/sets/default/style.css');
include_once $yarbb_path.'/theme/'.$yarbb_config['o_default_style'].'/plugins/markitup/sets/default/set.php';
// конец загрузки редактора
//парсер
require_once $yarbb_path . '/plugins/nbbc_custom.php';

$ptype = isset($_POST['ptype']) ? intval($_POST['ptype']) : 0;
$tid = isset($_GET['tid']) ? intval($_GET['tid']) : 0;
$fid = isset($_GET['fid']) ? intval($_GET['fid']) : 0;
if ($tid < 1 && $fid < 1 || $tid > 0 && $fid > 0)
    mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
// Загружаем инфу темы/форума
if ($tid) {
    $database->setQuery('SELECT f.id, f.forum_name, f.moderators, f.redirect_url, fp.post_replies, fp.post_topics, t.subject, t.descrip_t, t.closed, p.id AS post_id, p.poster_id, p.message, p.posted
				FROM #__forum_topics AS t 
				INNER JOIN #__forum_forums AS f ON f.id=t.forum_id 
				LEFT JOIN #__forum_posts AS p ON (t.last_post_id=p.id 
				AND p.poster_id='.$yarbb_user['id'].') 
				LEFT JOIN #__forum_forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$yarbb_user['g_id'].') 
				WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.id='.$tid);
} else {
    $database->setQuery('SELECT f.id, f.forum_name, f.moderators, f.redirect_url, fp.post_replies, fp.post_topics
				FROM #__forum_forums AS f 
				LEFT JOIN #__forum_forum_perms AS fp 
				ON (fp.forum_id=f.id AND fp.group_id='.$yarbb_user['g_id'].') 
				WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND f.id='.$fid);
}
$database->query();
if (!$database->getNumRows()) {
//exit("2");
    mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
}	
$rows = $database->loadAssocList();
$cur_posting = $rows[0];
// Is someone trying to post into a redirect forum?
if ($cur_posting['redirect_url'] != '') {
//exit("3");
    mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
}	
// Sort out who the moderators are and if we are currently a moderator (or an admin)
$mods_array = ($cur_posting['moderators'] != '') ? unserialize($cur_posting['moderators']) : array();
$is_admmod = ($yarbb_user['g_id'] == YARBB_ADMIN || ($yarbb_user['g_id'] == YARBB_MOD && array_key_exists($yarbb_user['username'], $mods_array)) || $yarbb_user['g_global_moderation']) ? true : false;

// Do we have permission to post?
if ((($tid && (($cur_posting['post_replies'] == '' && $yarbb_user['g_post_replies'] == '0') || $cur_posting['post_replies'] == '0')) ||
                ($fid && ((!isset($_GET['type']) && $ptype == '0')) && (($cur_posting['post_topics'] == '' && $yarbb_user['g_post_topics'] == '0') || $cur_posting['post_topics'] == '0'))  ||
                (isset($cur_posting['closed']) && $cur_posting['closed'] == '1')) && !$is_admmod) {
//exit("4");
    mosRedirect(sefRelToAbs(YARBB_URL.'&amp;task=access&amp;action=noperm'));
}
// Start with a clean slate
$errors = array();
// Did someone just hit "Submit" or "Preview"?
if (isset($_POST['form_sent'])) {
    // Make sure form_user is correct
    if (($yarbb_user['is_guest'] && $_POST['form_user'] != 'Guest') || (!$yarbb_user['is_guest'] && $_POST['form_user'] != $yarbb_user['username'])) {
        //exit("5");
        mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
    }
    // Проверка флуда
    if (!$yarbb_user['is_guest'] && !isset($_POST['preview']) && $yarbb_user['last_post'] != '' && (time() - $yarbb_user['last_post']) < $yarbb_user['g_post_flood'])

        $errors[] = _Y_YARFLOODST.' '.$yarbb_user['g_post_flood'].' '._Y_YARFLOODEND;

    // If it's a new topic
    if ($fid) {
        $subject = yarbb_trim($_POST['req_subject']);
        $descrip_t = yarbb_trim($_POST['descrip_t']);
        if ($subject == '')
            $errors[] = _Y_YANOVSUBJ;
        else if (yarbb_strlen($subject) > 100)
            $errors[] = _Y_YANOVSUBJ2;
        else if ($yarbb_config['p_subject_all_caps'] == '0' && strtoupper($subject) == $subject && ($yarbb_user['g_id'] > YARBB_MOD && !$yarbb_user['g_global_moderation']))
            $subject = ucwords(strtolower($subject));

        // If it is a topic it may contain a search labels
        $labels = yarbb_trim((!empty($yarbb_config['o_topic_labels']) && isset($_POST['unreq_labels']))? $_POST['unreq_labels']: '');
        // cleanup string
        $labels = implode_labels( explode_labels($labels) );


    }
    // If the user is logged in we get the username and e-mail from $yarbb_user
    if (!$yarbb_user['is_guest']) {
        $username = $yarbb_user['username'];
        $email = $yarbb_user['email'];
    }
    // Otherwise it should be in $_POST
    else {

        // капча
        if ($yarbb_config['o_guest_post_captchabox'] == '1') {
            session_name(mosMainFrame::sessionCookieName());
            session_start();
            $captcha = strval(mosGetParam($_POST, 'captcha', null));
            $captcha_keystring =mosGetParam($_SESSION,'captcha_keystring');
            if($captcha_keystring!== $captcha) {
                $errors[] = _Y_IMGMISTMACH;
                unset($_SESSION['captcha_keystring']);
            }
            session_unset();
            session_write_close();
        }

        $username = trim($_POST['req_username']);
        $email = strtolower(trim(($yarbb_config['p_force_guest_email'] == '1') ? $_POST['req_email'] : $_POST['email']));

        // It's a guest, so we have to validate the username
        if (strlen($username) < 2)
            $errors[] = _BAD_USER_LOGIN;
        else if (!strcasecmp($username, 'Guest') || !strcasecmp($username, _Y_YARGUEST))
            $errors[] = _Y_YAVALIDUSR;
        else if (preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $username))
            $errors[] = _Y_YAVALIDUSRIP;
        if ((strpos($username, '[') !== false || strpos($username, ']') !== false) && strpos($username, '\'') !== false && strpos($username, '"') !== false)
            $errors[] = _BAD_USER_LOGIN;
        if (preg_match('#\[b\]|\[/b\]|\[u\]|\[/u\]|\[i\]|\[/i\]|\[color|\[/color\]|\[quote\]|\[quote=|\[/quote\]|\[code\]|\[/code\]|\[img\]|\[/img\]|\[url|\[/url\]|\[email|\[/email\]#i', $username))
            $errors[] = _BAD_USER_LOGIN;

        // Проверить пользователя на запрещенные слова
        $temp = censor_words($username);
        if ($temp != $username)
            $errors[] = _Y_YAVALIDUSR2;

        // Проверка имени пользователя
        //s
        $database->setQuery('SELECT username FROM #__forum_users WHERE username=\''.$database->getEscaped($username).'\' OR username=\''.$database->getEscaped(preg_replace('/[^\w]/', '', $username)).'\'');
        $database->query();

        if ($database->getNumRows()) {
            $busy = $database->loadResult();
            $errors[] = _REGWARN_INUSE.' '.yarbb_htmlspecialchars($busy).'. '._Y_YAVALIDUSR3;
        }
        if ($yarbb_config['p_force_guest_email'] == '1' || $email != '') {
            require $yarbb_admin_path.'/include/email.php';
            if (!is_valid_email($email))
                $errors[] = _REGWARN_MAIL;
        }
    }

    // Clean up message from POST
    $message = yarbb_linebreaks(yarbb_trim($_POST['req_message']));

// Склейка сообщений старт
    $merged=false;
    if (!$yarbb_user['is_guest'] && !$fid && (($is_admmod && intval($_POST['merge'])==1) || !$is_admmod) && $cur_posting['poster_id']!=NULL && $cur_posting['message']!=NULL && time()-$cur_posting['posted']<$yarbb_config['o_merge_timeout']) {
        $message= yarbb_linebreaks(yarbb_trim("[color=#808080][i]"._YAR_USER_WHO_ADD_CONTENT.":  ".date('m.d.Y H:i:s').": [/i][/color]")) . "\n" . $message;
        $merged=true;
    }
// Склейка сообщений конец
    if ($message == '')
        $errors[] = _Y_YANOMESS;
    else if (strlen($message) > 65535)
        $errors[] = _Y_YANOMESS;
    else if ($yarbb_config['p_message_all_caps'] == '0' && strtoupper($message) == $message && ($yarbb_user['g_id'] > YARBB_MOD && !$yarbb_user['g_global_moderation']))
        $message = ucwords(strtolower($message));
    // Валидация синтаксиса ББ кодов
    /*if ($yarbb_config['p_message_bbcode'] == '1' && strpos($message, '[') !== false && strpos($message, ']') !== false) {
		$message = preparse_bbcode($message, $errors);
	}*/
    require $yarbb_admin_path.'/include/search_idx.php';
    $hide_smilies = isset($_POST['hide_smilies']) ? 1 : 0;
    $subscribe = isset($_POST['subscribe']) ? 1 : 0;
    $now = time();
    // Did everything go according to plan?
    if (empty($errors) && !isset($_POST['preview'])) {
        // If it's a reply
        if ($tid) {
            if (!$yarbb_user['is_guest']) {
                // Создать новое сообщение
                if ($merged) {
                    //s
                    $message = $cur_posting['message'] . "\n\n" . $message;
                    $database->setQuery('UPDATE #__forum_posts
									SET message=\''.$database->getEscaped($message).'\' 
									WHERE  id='.$cur_posting['post_id']);
                    $database->query();
                    $new_pid=$cur_posting['post_id'];
                    //exit("103");
                }
                else {
                    // Создать новое сообщение
                    $sql='INSERT INTO #__forum_posts (poster, poster_id, poster_ip, message, hide_smilies, posted, topic_id, userimage)
								VALUES(\''.$database->getEscaped($username).'\', '.$yarbb_user['id'].', \''.get_remote_address().'\', \''.$database->getEscaped($message).'\', \''.$hide_smilies.'\', '.$now.', '.$tid.', \'' . $name . '\')';
                    $database->setQuery($sql);
                    $database->query();

                    $new_pid = $database->insertid();
                }
// MERGE POSTS BEGIN
                if ($yarbb_config['o_subscriptions'] == '1' && $subscribe)
// MERGE POSTS END
                {
                    //s
                    $database->setQuery('SELECT 1 FROM #__forum_subscriptions
									WHERE user_id='.$yarbb_user['id'].' 
									AND topic_id='.$tid);
                    $database->query();
                    //exit("105");
                    if (!$database->getNumRows()) {
                        $database->setQuery('INSERT INTO #__forum_subscriptions (user_id, topic_id)
										VALUES('.$yarbb_user['id'].' ,'.$tid.')');
                        $database->query();
                        //exit("106");
                    }
                }
            }
            else {
                // Гость создает новый пост
                $email_sql = ($yarbb_config['p_force_guest_email'] == '1' || $email != '') ? '\''.$email.'\'' : 'NULL';
                $database->setQuery('INSERT INTO #__forum_posts (poster, poster_ip, poster_email, message, hide_smilies, posted, topic_id) VALUES(\''.$database->getEscaped($username).'\', \''.get_remote_address().'\', '.$email_sql.', \''.$database->getEscaped($message).'\', \''.$hide_smilies.'\', '.$now.', '.$tid.')');
                $database->query();
                $new_pid = $database->insertid();
            }
            // Количество ответов в теме
            $database->setQuery('SELECT COUNT(id) FROM #__forum_posts WHERE topic_id='.$tid);
            $num_replies = $database->loadResult() - 1;
            // Обновить тему
            $database->setQuery('UPDATE #__forum_topics SET num_replies='.$num_replies.', last_post='.$now.', last_post_id='.$new_pid.', last_poster=\''.$database->getEscaped($username).'\' WHERE id='.$tid);
            $database->query();
            update_search_index('post', $new_pid, $message);
            update_forum($cur_posting['id']);

            // Should we send out notifications?
            if ($yarbb_config['o_subscriptions'] == '1' && !$merged) {
                // Get the post time for the previous post in this topic
                $database->setQuery('SELECT posted FROM #__forum_posts
								WHERE topic_id='.$tid.' 
								ORDER BY id DESC LIMIT 1, 1');
                $previous_post_time = $database->loadResult();
                // Get any subscribed users that should be notified (banned users are excluded)
                $database->setQuery('SELECT u.id, u.email, u.notify_with_post, u.language
									FROM #__forum_users AS u 
									INNER JOIN #__forum_subscriptions AS s ON u.id=s.user_id 
									LEFT JOIN #__forum_forum_perms AS fp 
									ON (fp.forum_id='.$cur_posting['id'].' AND fp.group_id=u.group_id) 
									LEFT JOIN #__session AS o ON (u.id=o.userid AND o.guest=0)
									LEFT JOIN #__forum_bans AS b ON u.username=b.username 
									WHERE b.username IS NULL AND COALESCE(o.time, u.last_visit)>'.$previous_post_time.' 
									AND (fp.read_forum IS NULL OR fp.read_forum=1) 
									AND s.topic_id='.$tid.' 
									AND u.id!='.intval($yarbb_user['id']));
                $database->query();
                if ($database->getNumRows()) {
                    //dd require_once $yarbb_admin_path.'/include/email.php';
                    $notification_emails = array();
                    // Loop through subscribed users and send e-mails
                    $rows=$database->loadAssocList();

                    foreach ($rows as $cur_subscriber ) {
                        // Is the subscription e-mail for $cur_subscriber['language'] cached or not?
                        if (!isset($notification_emails[$mosConfig_lang])) {
                            if (file_exists($yarbb_path.'/inc/mail_templates/'.$mosConfig_lang.'/new_reply.tpl')) {
                                // Load the "new reply" template
                                $mail_tpl = trim(file_get_contents($yarbb_path.'/inc/mail_templates/'.$mosConfig_lang.'/new_reply.tpl'));
                                // Load the "new reply full" template (with post included)
                                $mail_tpl_full = trim(file_get_contents($yarbb_path.'/inc/mail_templates/'.$mosConfig_lang.'/new_reply_full.tpl'));
                                // The first row contains the subject (it also starts with "Subject:")
                                $query = "SELECT id FROM #__menu WHERE link='index.php?option=com_forum'";
                                $database->setQuery($query);
                                $yarbb_Itemid = $database->loadResult();
                                $yarbb_path_1 = "index.php?option=com_forum&Itemid=".$yarbb_Itemid;

                                $first_crlf = strpos($mail_tpl, "\n");
                                $mail_subject = trim(substr($mail_tpl, 8, $first_crlf-8));
                                $mail_message = trim(substr($mail_tpl, $first_crlf));
                                $first_crlf = strpos($mail_tpl_full, "\n");
                                $mail_subject_full = trim(substr($mail_tpl_full, 8, $first_crlf-8));
                                $mail_message_full = trim(substr($mail_tpl_full, $first_crlf));
                                $mail_subject = str_replace('<topic_subject>', '\''.$cur_posting['subject'].'\'', $mail_subject);
                                $mail_message = str_replace('<topic_subject>', '\''.$cur_posting['subject'].'\'', $mail_message);
                                $mail_message = str_replace('<replier>', $username, $mail_message);
                                $mail_message = str_replace('<post_url>', $mosConfig_live_site.'/'.$yarbb_path_1.'&task=viewtopic&pid='.$new_pid.'#p'.$new_pid, $mail_message);
                                $mail_message = str_replace('<unsubscribe_url>', $mosConfig_live_site.'/'.$yarbb_path_1.'&task=misc&unsubscribe='.$tid, $mail_message);
                                $mail_message = str_replace('<board_mailer>', $yarbb_config['o_board_title'].' '._Y_YARROBOTMAIL, $mail_message);
                                $mail_subject_full = str_replace('<topic_subject>', '\''.$cur_posting['subject'].'\'', $mail_subject_full);
                                $mail_message_full = str_replace('<topic_subject>', '\''.$cur_posting['subject'].'\'', $mail_message_full);
                                $mail_message_full = str_replace('<replier>', $username, $mail_message_full);
                                $mail_message_full = str_replace('<message>', $message, $mail_message_full);
                                $mail_message_full = str_replace('<post_url>', $mosConfig_live_site.'/'.$yarbb_path_1.'&task=viewtopic&pid='.$new_pid.'#p'.$new_pid, $mail_message_full);
                                $mail_message_full = str_replace('<unsubscribe_url>', $mosConfig_live_site.'/'.$yarbb_path_1.'&task=misc&unsubscribe='.$tid, $mail_message_full);
                                $mail_message_full = str_replace('<board_mailer>', $yarbb_config['o_board_title'].' '._Y_YARROBOTMAIL, $mail_message_full);
                                $notification_emails[$mosConfig_lang][0] = $mail_subject;
                                $notification_emails[$mosConfig_lang][1] = $mail_message;
                                $notification_emails[$mosConfig_lang][2] = $mail_subject_full;
                                $notification_emails[$mosConfig_lang][3] = $mail_message_full;
                                $mail_subject = $mail_message = $mail_subject_full = $mail_message_full = null;
                            }
                        }
                        // We have to double check here because the templates could be missing
                        if (isset($notification_emails[$mosConfig_lang])) {
                            if ($cur_subscriber['notify_with_post'] == '0')
                                yarbb_mail($cur_subscriber['email'], $notification_emails[$mosConfig_lang][0], $notification_emails[$mosConfig_lang][1]);
                            else
                                yarbb_mail($cur_subscriber['email'], $notification_emails[$mosConfig_lang][2], $notification_emails[$mosConfig_lang][3]);
                        }
                    }
                }
            }
        }
        // If it's a new topic
        else if ($fid) {
            $icon_topic = $_POST['icon_topic'];
            // Создать тему
            ////////////////////////////////////
            if(isset($ptype)) // Si c'est un sondage
            {
                if ($ptype == 3) {
                    $database->setQuery('INSERT INTO #__forum_topics (poster, subject, descrip_t, posted, last_post, last_poster, forum_id, icon_topic, yes, no, labels) VALUES(\'' . $database->getEscaped($username) . '\', \'' . $database->getEscaped($subject) . '\', \'' . $database->getEscaped($descrip_t) . '\', ' . $now . ', ' . $now . ', \'' . $database->getEscaped($username) . '\', \'' . $fid . '\', \''.$icon_topic.'\', \'' . $database->getEscaped($yesval) . '\', \'' . $database->getEscaped($noval) . '\', \''.$database->getEscaped($labels).'\')');
                    $database->query();
                }
                else {
                    $database->setQuery('INSERT INTO #__forum_topics (poster, subject, descrip_t, posted, last_post, last_poster, forum_id, icon_topic, labels) VALUES(\'' . $database->getEscaped($username) . '\', \'' . $database->getEscaped($subject) . '\', \'' . $database->getEscaped($descrip_t) . '\',' . $now . ', ' . $now . ', \'' . $database->getEscaped($username) . '\', \'' . $fid . '\', \''.$icon_topic.'\',  \''.$database->getEscaped($labels).'\')');
                    $database->query();
                }
                $new_tid = $database->insertid();

            } else {

                $icon_topic = $_POST['icon_topic'];
                /////////////////////////////////////

                $database->setQuery('INSERT INTO #__forum_topics (poster, subject, posted, last_post, last_poster, forum_id, icon_topic, labels) VALUES(\''.$database->getEscaped($username).'\', \''.$database->getEscaped($subject).'\', '.$now.', '.$now.', \''.$database->getEscaped($username).'\', '.$fid.', \''.$icon_topic.'\', \''.$database->getEscaped($labels).'\')');
                $database->query();
                //exit("102");

                $new_tid = $database->insertid();
            }
            if (!$yarbb_user['is_guest']) {
                // To subscribe or not to subscribe, that ...
                if ($yarbb_config['o_subscriptions'] == '1' && (isset($_POST['subscribe']) && $_POST['subscribe'] == '1')) {
                    $database->setQuery('INSERT INTO #__forum_subscriptions (user_id, topic_id) VALUES('.$yarbb_user['id'].' ,'.$new_tid.')');
                    $database->query();
                }
                // Create the post ("topic post")
                $database->setQuery('INSERT INTO #__forum_posts (poster, poster_id, poster_ip, message, hide_smilies, posted, topic_id) VALUES(\''.$database->getEscaped($username).'\', '.$yarbb_user['id'].', \''.get_remote_address().'\', \''.$database->getEscaped($message).'\', \''.$hide_smilies.'\', '.$now.', '.$new_tid.')');
                $database->query();
                //exit("100");
            }
            else {

                // Create the post ("topic post")
                $email_sql = ($yarbb_config['p_force_guest_email'] == '1' || $email != '') ? '\''.$email.'\'' : 'NULL';
                $database->setQuery('INSERT INTO #__forum_posts (poster, poster_ip, poster_email, message, hide_smilies, posted, topic_id) VALUES(\''.$database->getEscaped($username).'\', \''.get_remote_address().'\', '.$email_sql.', \''.$database->getEscaped($message).'\', \''.$hide_smilies.'\', '.$now.', '.$new_tid.')');
                $database->query();
                //exit("101");
            }
            $new_pid = $database->insertid();
            // Update the topic with last_post_id
            $database->setQuery('UPDATE #__forum_topics SET last_post_id='.$new_pid.' WHERE id='.$new_tid);
            $database->query();

            update_search_index('post', $new_pid, $message, $subject);
            update_forum($fid);
        }

        if (!$yarbb_user['is_guest']) {
            $low_prio = ($db_type == 'mysql') ? 'LOW_PRIORITY ' : '';
            if ($merged) {
                $database->setQuery('UPDATE '.$low_prio.'#__forum_users SET last_post='.$now.' WHERE id='.$yarbb_user['id']);
                $database->query();
            }
            else {
                $database->setQuery('UPDATE '.$low_prio.'#__forum_users SET num_posts=num_posts+1, last_post='.$now.' WHERE id='.$yarbb_user['id']);
                $database->query();
            }
        }
// MERGE POSTS END     
//exit("7");
//добавляем номер страницы темы		
$num_pages_topic = ceil(($num_replies + 1) / $yarbb_user['disp_posts']);
        mosRedirect(sefRelToAbs(YARBB_URL.'&amp;task=viewtopic&amp;page='.$num_pages_topic.'&amp;pid='.$new_pid).'#p'.$new_pid);
    }
}

// If a topic id was specified in the url (it's a reply).
if ($tid) {
    $action = _Y_YARPOSTREAPLY;
    $form = '<form id="post" method="post" action="'.sefRelToAbs(YARBB_URL.'&amp;task=post&amp;action=post&amp;tid='.$tid).'"  onsubmit="this.submit.disabled=true;if(process_form(this)){return true;}else{this.submit.disabled=false;return false;}" enctype="multipart/form-data">';

    // If a quote-id was specified in the url.
    if (isset($_GET['qid'])) {
        $qid = intval($_GET['qid']);
        if ($qid < 1) {
            //exit("8");
            mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
        }
        $database->setQuery('SELECT poster, message FROM #__forum_posts WHERE id='.$qid.' AND topic_id='.$tid);
        $database->query();
        if (!$database->getNumRows()) {
            //exit("9");
            mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
        }
        list($q_poster, $q_message) = $database->loadRow();
        $q_message = str_replace('[img]', '[url]', $q_message);
        $q_message = str_replace('[/img]', '[/url]', $q_message);
        $q_message = yarbb_htmlspecialchars($q_message);

        if ($yarbb_config['p_message_bbcode'] == '1') {
            // If username contains a square bracket, we add "" or '' around it (so we know when it starts and ends)
            if (strpos($q_poster, '[') !== false || strpos($q_poster, ']') !== false) {
                if (strpos($q_poster, '\'') !== false)
                    $q_poster = '"'.$q_poster.'"';
                else
                    $q_poster = '\''.$q_poster.'\'';
            }
            else {
                // Get the characters at the start and end of $q_poster
                $ends = substr($q_poster, 0, 1).substr($q_poster, -1, 1);
                // Deal with quoting "Username" or 'Username' (becomes '"Username"' or "'Username'")
                if ($ends == '\'\'')
                    $q_poster = '"'.$q_poster.'"';
                else if ($ends == '""')
                    $q_poster = '\''.$q_poster.'\'';
            }
            $quote = '[quote='.$q_poster.']'.$q_message.'[/quote]'."\n";
        }
        else
            $quote = '> '.$q_poster.' '._Y_YARWROTE.':'."\n\n".'> '.$q_message."\n";
    }
    $forum_name = '<a href="'.sefRelToAbs(YARBB_URL.'&amp;task=viewforum&amp;id='.$cur_posting['id']).'">'.yarbb_htmlspecialchars($cur_posting['forum_name']).'</a>';
}
// If a forum_id was specified in the url (new topic).
else if ($fid) {
    $action = _Y_YARNEWTOP;
    $form = '<form id="post" method="post" action="'.sefRelToAbs(YARBB_URL.'&amp;task=post&amp;action=post&amp;fid='.$fid).'" enctype="multipart/form-data" onsubmit="return process_form(this)">';
    $forum_name = yarbb_htmlspecialchars($cur_posting['forum_name']);
}
else {
//exit("10");
    mosRedirect(sefRelToAbs(YARBB_URL), _Y_404);
}

echo $mainframe->setPageTitle( yarbb_htmlspecialchars($yarbb_config['o_board_title']));

$required_fields = array('req_email' => _CMN_EMAIL, 'req_subject' => _CAPTION, 'req_message' => _Y_YARMESS4);
$focus_element = array('post');
if (!$yarbb_user['is_guest'])
    $focus_element[] = ($fid) ? 'req_subject' : 'req_message';
else {
    $required_fields = array('req_email' => _CMN_EMAIL, 'req_subject' => _CAPTION, 'req_message' => _Y_YARMESS4, 'req_username' => _REGISTER_NAME, 'req_image' => _Y_TXTIMG);
    $focus_element[] = 'req_username';
}
?>

<div class="linkst">
    <div class="inbox">
        <ul>
            <li><a href="<?php echo sefRelToAbs(YARBB_URL) ?>"><?php echo _Y_INDEX; ?></a>
            <li>&nbsp;&raquo;&nbsp;<?php echo $forum_name ?>
                <?php if (isset($cur_posting['subject'])) echo '</li><li>&nbsp;&raquo;&nbsp;'.yarbb_htmlspecialchars($cur_posting['subject']) ?>
            </li>
        </ul>
    </div>
</div>
<?php
// Вывод ошибок
if (!empty($errors)) {
    ?>
<div id="posterror" class="block">
    <h2><span><?php echo _Y_YARERROR; ?></span></h2>
    <div class="box">
        <div class="inbox">
            <p><?php echo _Y_YARERRORINF; ?></p>
            <ul>
                    <?php
                    while (list(, $cur_error) = each($errors))
                        echo "\t\t\t\t".'<li><strong>'.$cur_error.'</strong></li>'."\n";
                    ?>
            </ul>
        </div>
    </div>
</div>
    <?php
}
else if (isset($_POST['preview'])) {
    $preview_message = $bbcode->Parse($message, $hide_smilies);
    ?>
<div id="postpreview" class="blockpost">
    <h2><span><?php echo _PREVIEW; ?></span></h2>
    <div class="box">
        <div class="inbox">
            <div class="postright">
                <div class="postmsg"> <?php echo $preview_message."\n" ?> </div>
            </div>
        </div>
    </div>
</div>
    <?php
}
if (!isset($_GET['type'])) {
    $cur_index = 100;
    if($ptype == '0') {
        ?>
<div class="blockform">
    <h2><span><?php echo $action ?></span></h2>
    <div class="box"> <?php echo $form."\n" ?>
                <?php
            }
            ?>
        <div class="inform">
            <fieldset>
                <legend><?php echo _Y_YARWROTELEG; ?></legend>
                <div class="infldset txtarea">
                    <input type="hidden" name="form_sent" value="1" />
                    <input type="hidden" name="form_user" value="<?php echo (!$yarbb_user['is_guest']) ? yarbb_htmlspecialchars($yarbb_user['username']) : 'Guest'; ?>" />
                        <?php
                        if ($yarbb_user['is_guest']) {
                            $email_label = ($yarbb_config['p_force_guest_email'] == '1') ? '<strong>'._CMN_EMAIL.'</strong>' : _CMN_EMAIL;
                            $email_form_name = ($yarbb_config['p_force_guest_email'] == '1') ? 'req_email' : 'email';
                            ?>
                    <label class="conl"><strong><?php echo _REGISTER_NAME; ?></strong><br />
                        <input type="text" name="req_username" value="<?php if (isset($_POST['req_username'])) echo yarbb_htmlspecialchars($username); ?>" size="25" maxlength="25" tabindex="<?php echo $cur_index++ ?>" />
                        <br />
                    </label>
                    <label class="conl"><?php echo $email_label ?><br />
                        <input type="text" name="<?php echo $email_form_name ?>" value="<?php if (isset($_POST[$email_form_name])) echo yarbb_htmlspecialchars($email); ?>" size="50" maxlength="50" tabindex="<?php echo $cur_index++ ?>" />
                        <br />
                    </label>
                    <div class="clearer"></div>
                            <?php
                        }
                        if ($fid):
                            $d = dir($yarbb_path.'/images/icons');

                            while (($entry = $d->read()) !== false) {
                                if (substr($entry, strlen($entry)-4) == '.gif') {
                                    $icons_topic[] = substr($entry, 0, strlen($entry)-4);
                                }
                            }
                            $d->close();
                            if (count($icons_topic) > 1) {
                                while (list(, $temp) = @each($icons_topic)) {
                                    echo '<input type="radio" name="icon_topic" value="'.$temp.'" />&nbsp;<img src="'.$yarbb_live.'/images/icons/'.$icons_topic[$temp-1].'.gif" alt="'.$temp.'" />&nbsp;';
                                }
                                echo '<input type="radio" name="icon_topic" value="0" checked="checked" />&nbsp;';
                            }
                            ?>
                    <br />
                    <label><strong><?php echo _CAPTION; ?></strong><br />
                        <input class="longinput" type="text" name="req_subject" value="<?php if (isset($_POST['req_subject'])) echo yarbb_htmlspecialchars($subject); ?>" size="80" maxlength="70" tabindex="<?php echo $cur_index++ ?>" />
                        <br />
                    </label>
                    <label><?php echo _DESCRIPTION; ?><br />
                        <input class="longinput" type="text" name="descrip_t" value="<?php if (isset($_POST['descrip_t'])) echo yarbb_htmlspecialchars($descrip_t); ?>" size="80" maxlength="70" tabindex="<?php echo $cur_index++ ?>" />
                        <br />
                    </label>
                        <?php endif; ?>
                    <label><strong><?php echo _Y_MESSAGE; ?></strong><br />
                        <script type="text/javascript">
                            <!--
                            $(document).ready(function()	{
                                // Add markItUp! to your textarea in one line
                                // $('textarea').markItUp( { Settings }, { OptionalExtraSettings } );
                                $('#req_message').markItUp(mySettings);

                                // You can add content from anywhere in your page
                                // $.markItUp( { Settings } );
                                $('.add').click(function() {
                                    $.markItUp( { 	openWith:'<opening tag>',
                                        closeWith:'<\/closing tag>',
                                        placeHolder:"New content"
                                    }
                                );
                                    return false;
                                });

                                // And you can add/remove markItUp! whenever you want
                                // $(textarea).markItUpRemove();
                                $('.toggle').click(function() {
                                    if ($("#req_message.markItUpEditor").length === 1) {
                                        $("#req_message").markItUpRemove();
                                        $("span", this).text("get markItUp! back");
                                    } else {
                                        $('#req_message').markItUp(mySettings);
                                        $("span", this).text("remove markItUp!");
                                    }
                                    return false;
                                });


                                $('#emoticons a').click(function() {
                                    emoticon = $(this).attr("title");
                                    $.markItUp( { replaceWith:emoticon } );
                                });

                            });
                            -->
                        </script>
                        <div id="emoticons">
                                <?php

// Display the smiley set
                                $smiley_dups = array();
                                $num_smilies = count($smiley_text);
                                for ($i = 0; $i < $num_smilies; ++$i) {
                                    // Is there a smiley at the current index?
                                    if (!isset($smiley_text[$i]))
                                        continue;
                                    if (!in_array($smiley_img[$i], $smiley_dups))
                                        echo "\t\t\t\t\t\t\t".'<a href="#" title=" '.$smiley_text[$i].' "><img src="'.$yarbb_live.'/images/smilies/'.$smiley_img[$i].'" alt="'.$smiley_text[$i].'" /></a>'."\n";
                                    $smiley_dups[] = $smiley_img[$i];
                                }
                                ?>
                        </div>


                        <textarea cols="" rows="" name="req_message" id="req_message" tabindex="<?php echo $cur_index++ ?>"><?php echo isset($_POST['req_message']) ? yarbb_htmlspecialchars($message) : (isset($quote) ? $quote : ''); ?></textarea>
                        <br />
                    </label>
                        <?php if ($fid && !empty($yarbb_config['o_topic_labels'])): ?>
                    <div class="unreq_labels"><label><strong><?php echo _Y_TAGS; ?></strong><br />
                        <input class="longinput" type="text" name="unreq_labels" value="<?php if (isset($_POST['unreq_labels'])) echo yarbb_htmlspecialchars(substr($labels,1,-1)); ?>" size="80" maxlength="70" tabindex="<?php echo $cur_index++ ?>" />
                        <br />
                        <font size="1"><?php echo _Y_TAGS2; ?></font></label></div>
                        <?php endif; ?>
                </div>
            </fieldset>
                <?php
                $checkboxes = array();
                if (!$yarbb_user['is_guest']) {
                    if ($yarbb_config['o_smilies'] == '1')
                        $checkboxes[] = '<label><input type="checkbox" name="hide_smilies" value="1" tabindex="'.($cur_index++).'"'.(isset($_POST['hide_smilies']) ? ' checked="checked"' : '').' />'._Y_YARSMILEHID;
// Склейка сообщений
                    if ($is_admmod)
                        $checkboxes[] = '<label><input type="checkbox" name="merge" value="1" checked="checked" />'._Y_YARMERGEADD;
// Конец склейки сообщений
                    if ($yarbb_config['o_subscriptions'] == '1')
                        $checkboxes[] = '<label><input type="checkbox" name="subscribe" value="1" tabindex="'.($cur_index++).'"'.(isset($_POST['subscribe']) ? ' checked="checked"' : '').' />'._Y_YAROPSUBS;
                }
                else if ($yarbb_config['o_smilies'] == '1')
                    $checkboxes[] = '<label><input type="checkbox" name="hide_smilies" value="1" tabindex="'.($cur_index++).'"'.(isset($_POST['hide_smilies']) ? ' checked="checked"' : '').' />'._Y_YARSMILEHID;
                if (!empty($checkboxes)) {
                    ?>
        </div>
        <div class="inform">
            <fieldset>
                <legend><?php echo _Y_YAROTIONS; ?></legend>
                <div class="infldset">
                    <div class="rbox"> <?php echo implode('<br /></label>'."\n\t\t\t\t", $checkboxes).'<br /></label>'."\n" ?> </div>
                </div>
            </fieldset>
                    <?php
                }
                ?>
        </div>
            <?php
// капча
            if (($yarbb_config['o_guest_post_captchabox'] == '1') and ($yarbb_user['is_guest'])): ?>
        <div class="captcha"> <img id="captchaimg" alt="<?php echo _PRESS_HERE_TO_RELOAD_CAPTCHA?>" onclick="document.emailForm.captchaimg.src='<?php echo JPATH_SITE; ?>/includes/libraries/kcaptcha/index.php?session=<?php echo mosMainFrame::sessionCookieName() ?>&' + new String(Math.random())" src="<?php echo JPATH_SITE; ?>/includes/libraries/kcaptcha/index.php?session=<?php echo mosMainFrame::sessionCookieName() ?>" />
            <label for="captcha" id="lbl_captcha"><?php echo _PLEASE_ENTER_CAPTCHA; ?></label>
            <input name="captcha" type="text" class="inputbox" size="30" />
        </div>
            <?php endif; ?>
        <input type="submit" name="submit" value="<?php echo _SUBMIT_BUTTON; ?>" tabindex="<?php echo $cur_index++ ?>" accesskey="s" />
        <input name="submit" type="button" value="<?php echo _Y_YARATTACHFILE; ?>" onclick="javascript:PopUp('<?php echo sefRelToAbs(YARBB_URL_ATTACH . '&amp;task=attach');?>', 'gest', '850', '530', 'resizable=yes, location=no, menubar=no, status=no, scrollbars=yes')" />
        <input type="submit" name="preview" value="<?php echo _Y_PREVIEW; ?>" tabindex="<?php echo $cur_index++ ?>" accesskey="p" />
        <input name="" type="button" onclick="javascript:history.go(-1)" value="<?php echo _CANCEL; ?>" />
            <?php echo '</form>'; ?>
        <script type="text/javascript">
        function example_ajax_request() {
  $('#loadattach').html('<p align="center"><img src="<?php echo $yarbb_live.'/theme/'.$yarbb_config['o_default_style'].'/images/loading.gif' ?>" alt="" /></p>');
  $('#loadattach').load("<?php echo sefRelToAbs(YARBB_URL_ATTACH.'&task=attach') ?>");
}
        </script>
        <div id="loadattach"></div>
            <?php
            //include $yarbb_path.'/task/attach.php';
        };
        ?>
    </div>
    <?php
// Check to see if the topic review is to be displayed.
    if ($tid && $yarbb_config['o_topic_review'] != '0') {

        $database->setQuery('SELECT poster, message, hide_smilies, posted
                                FROM #__forum_posts
                                WHERE topic_id='.$tid.'
                                ORDER BY id DESC LIMIT '.$yarbb_config['o_topic_review']);
        ?>
    <div id="postreview" class="blockpost">
        <h2><span><?php echo _Y_YAOBZOR; ?></span></h2>
            <?php
            //Set background switching on
            $bg_switch = true;
            $post_count = 0;
            //s
            $rows=$database->loadAssocList();
            foreach ($rows as $cur_post ) {
                // Switch the background color for every message.
                $bg_switch = ($bg_switch) ? $bg_switch = false : $bg_switch = true;
                $vtbg = ($bg_switch) ? ' roweven' : ' rowodd';
                $post_count++;
                $cur_post['message'] = $bbcode->Parse($cur_post['message'], $cur_post['hide_smilies']);
                ?>
        <div class="box<?php echo $vtbg ?>">
            <div class="inbox">
                <div class="postleft">
                    <dl>
                        <dt><strong><?php echo yarbb_htmlspecialchars($cur_post['poster']) ?></strong></dt>
                        <dd><?php echo format_time($cur_post['posted']) ?></dd>
                    </dl>
                </div>
                <div class="postright">
                    <div class="postmsg"> <?php echo $cur_post['message'] ?> </div>
                    <a onMouseOver="copyQ('<?php echo $cur_post['poster']; ?>');" href="javascript:pasteQ();"><?php echo _Y_YARPASTEQUOT; ?></a> &nbsp;<a onClick="javascript:pasteN('<?php echo $cur_post['poster']; ?>'); return false;" href="javascript:void(0)"><?php echo _Y_YARPASTEUSR; ?></a> </div>
            </div>
        </div>
                <?php
            }
            ?>
    </div>
</div>
    <?php
}